﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using RegOnline.RegOnlineService;
using System.IO;
using System.Text;
using RegOnline.Views;

namespace RegOnline
{
    public partial class UchebnPlanPage : Page
    {
        public MainViewModel ac;
        public bool editing;
        
        public UchebnPlanPage()
        {
            InitializeComponent();
        }

        
        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                ac = ((((Parent as Frame).Parent as Border).Parent as Grid).Parent as MainPage).Controller;
                if (ac == null) MessageBox.Show("ac нот лоадед!");

                ac.WorksLoaded += new EventHandler(ac_WorksLoaded);
                ac.ReqWorksLoaded += new EventHandler(ac_ReqWorksLoaded);
                ac.FileSaved += new EventHandler(ac_FileSaved);

                grupNameLabel.Content = ac.CurrentGroup.grupName;
                semNumLabel.Content = ac.CurrentSemestr.SemNum;
                disLabel.Content = ac.CurrentUchPlan.Dis.DisName;
                vidLabel.Content = ac.CurrentUchPlan.Vid.VidWorkName;

                themeBox.Text = "";
                themeVariant.Text ="";
                regNumberText.Content ="";
                dateRegText.Content = " ";
                saveTheme.IsEnabled = false;


                ac.LoadWork();
                ac.LoadReqWork();
                
            }
            catch (Exception exception )
            {
                ErrorWindow err = new ErrorWindow(exception);
                NavigationService.Navigate(new Uri("/login", UriKind.Relative));
            }

        }

        void ac_FileSaved(object sender, EventArgs e)
        {
            System.Threading.Thread.Sleep(1000);
            LoadingGrid.Visibility = System.Windows.Visibility.Collapsed;
            ac.LoadReqWork();
        }

        void ac_ReqWorksLoaded(object sender, EventArgs e)
        {
            foreach (var reqsWork in ac.ReqWorks)
            {
                reqsWork.StatusImageUrl = ImageController.GetPict(reqsWork);
            }
            reqsWorkDTODataGrid.ItemsSource = ac.ReqWorks;

            if (ac.ReqWorks.Count==0)
            {
                rectangle1.Visibility = System.Windows.Visibility.Visible;
                label1.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                rectangle1.Visibility = System.Windows.Visibility.Collapsed;
                label1.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        void ac_WorksLoaded(object sender, EventArgs e)
        {
            Work w = ac.Works.FirstOrDefault();
            ac.CurrentWork = ac.Works.FirstOrDefault(); 
            try
            {
                if (w != null) 
                {
                    themeBox.Text = w.theme;
                    themeVariant.Text = w.options.HasValue ? w.options.Value.ToString() : "Варианта нет";
                    regNumberText.Content = w.RegNum.HasValue ? w.RegNum.Value.ToString() : " ";
                    dateRegText.Content = w.RegDate.HasValue ? w.RegDate.Value.ToShortDateString() : " ";
                    saveTheme.IsEnabled = false;
                    
                    RegistredPanel.Visibility = System.Windows.Visibility.Visible;
                    NotRegistredPanel.Visibility = System.Windows.Visibility.Collapsed;

                }
                if (w.RegNum != null)
                {
                    button4.IsEnabled = false;
                }

            }
            catch (Exception)
            {
                // ErrorWindow err  = new ErrorWindow(ex);
                // ErrorWindow err  = new ErrorWindow(ex);
               // err.Show();
                RegistredPanel.Visibility = System.Windows.Visibility.Collapsed;
                NotRegistredPanel.Visibility = System.Windows.Visibility.Visible;

                themeBox.Text = "";
                themeVariant.Text = "";

               
            }



        }

        private void Save2_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                if (ac.CurrentWork != null && editing == true)
                {
                    themeBox.Text=ac.CurrentWork.theme;
                    ac.CurrentWork.options = Decimal.Parse(themeVariant.Text);
                    ac.UpdateWork();
                    saveTheme.IsEnabled = false;
                }
                else
                {
                    Work w = new Work();
                    w.theme = themeBox.Text;
                    w.options = Decimal.Parse(themeVariant.Text);
                    ac.InsertWorkTheme(w);
                    ac.LoadWork();
                    ac.LoadReqWork();
                    saveTheme.IsEnabled = false;
                }
            }
            catch
            {
            }
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                if (ac.CurrentWork == null)
                {
                    MessageWindow MW = new MessageWindow("Сначала сохраните тему работы!");
                    MW.Show();
                }

                else
                {
                    var stud = ac.User;
                    var semestr = ac.CurrentSemestr;
                    var Uch = ac.CurrentUchPlan;
                    var Req = reqsWorkDTODataGrid.SelectedItem as ReqsWork;
                    ac.CurrentReqWork = Req;
                    var W = worksDTODataGrid.SelectedItem as Work;


                    // фильтр
                    string exe, name;
                    exe = Convert.ToString(Req.LR.expdoc);
                    exe = exe.Replace(",", " ; ");
                    name = Req.LR.RR.nameReq;

                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter = name + " | " + exe;
                    openFileDialog.Multiselect = false;

                    if (openFileDialog.ShowDialog() == true)
                    {
                        LoadingGrid.Visibility = System.Windows.Visibility.Visible;

                        Stream stream = (Stream)openFileDialog.File.OpenRead();
                        var bytes = new byte[stream.Length];
                        stream.Read(bytes, 0, (int)stream.Length);
                        ac.SaveFile(bytes);
                    }

                }
            }
            catch (Exception ex)
            {
                ErrorWindow err = new ErrorWindow(ex);
                err.Show();
            }
            }
        

        

            
        private void Back_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            if (ac.CurrentWork != null)
            {

                var rw = ac.ReqWorks.Where(x=>x.LR.lWs.SistemNum.HasValue==false);
                if (rw.Count() != 0)
                {
                    MessageWindow MW = new MessageWindow("Перед регистрацией работы загрузите все документы по всем требованиям к работе!");
                    MW.Show(); 
                    
                }
                else
                {
                    ac.InsertWorkNum();
                    ac.LoadWork();
                }
            }
            else
            {
                MessageWindow MW = new MessageWindow("Сначала сохраните тему работы!");
                MW.Show(); 
               
            }
        }
         
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {

        }

         private void Del_Click (object отправителя, RoutedEventArgs е)
	         {
                 try
                 {
	                 var File = (reqsWorkDTODataGrid.SelectedItem as ReqsWork);
                     if (File.LR.lWs.SistemNum != null)
                     {
                         ac.DeleteResultWork(File.LR.lWs.SistemNum);
                         ac.ReqWorksLoaded += new EventHandler(ac_ReqWorksLoaded);
                         ac.LoadReqWork();
                     }
                 }
                 catch
                 {
                 }
	         }

         private void themeBox_TextChanged(object sender, TextChangedEventArgs e)
         {
             editing = true;
             saveTheme.IsEnabled = true;
         }

         private void themeVariant_TextChanged(object sender, TextChangedEventArgs e)
         {
             String OriginalValue = themeVariant.Text.Trim();
             int IntValue;
             if (OriginalValue.Length > 0 && !int.TryParse(OriginalValue, out IntValue))
             {
                 themeVariant.Text = OriginalValue.Substring(0, OriginalValue.Length - 1);
             }
         }
    }

}
